package com.woniuxy.usercoachassemble.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniuxy.usercoachassemble.configuration.RabbitmqConfiger;
import com.woniuxy.usercoachassemble.entity.*;
import com.woniuxy.usercoachassemble.service.*;
import org.example.Result;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Lucas
 * @since 2020-07-10
 */
@RestController
@RequestMapping("orders")
public class OrdersController {
    @Autowired
    private ChargeConfirmService chargeConfirmServiceImpl;
    @Autowired
    private OrdersService ordersServiceImpl;
    @Autowired
    private CoachInfoService CoachInfoServiceImpl;
    @Autowired
    private CoachTimeService coachTimeServiceImpl;
    @Autowired
    private TimeService timeServiceImpl;
    @Autowired
    private CourseService courseServiceImpl;
    @Autowired
    private CoachCourseService coachCourseServiceImpl;
    @Autowired
    private  AttentionService attentionServiceImpl;
    @Autowired
    private CommentService commentServiceImpl;
    @Autowired
    private UserinfoService userinfoServiceImpl;

    @Autowired
    private  AccountService accountServiceImpl;
    @Autowired
    private  CoachStudentService coachStudentServiceImpl;
   @Autowired
   private  InformController informController;
    @Autowired
    private  RabbitTemplate   rabbitTemplate;
    //教练增加一条订单 针对签约的学员 教练自己填写课时种类 时长 时间 ,status默认为0,更改空闲时间状态为0
    @RequestMapping("askorder")
    public Result addorders(Orders orders, HttpServletRequest request){
        //查询出教练的小时收费
        CoachInfo coachInfo= CoachInfoServiceImpl.query().eq("user_id",request.getIntHeader("userId")).one();
        double charge=coachInfo.getCharge();
        orders.setMoney(charge);
        orders.setCoachId(request.getIntHeader("userId"));
        ordersServiceImpl.save(orders);
        coachTimeServiceImpl.update().eq("coach_time_id",orders.getCoachTimeId()).set("status",0).update();
        return Result.Success();
    }



    //教练申请付款,上完课后更改状态为1
    @RequestMapping("pleasepay")
    public Result pleasepay(int ordersId){
        ordersServiceImpl.update().eq("orders_id",ordersId).set("status",1).update();
        return Result.Success(1);
    }
    //查询教练签约的学生
   @RequestMapping("allmystudent")
   public  Result allmystudent(HttpServletRequest request){
          int coachId=request.getIntHeader("userId");
       List<CoachStudent> coachStudents = coachStudentServiceImpl.query().eq("coach_id", coachId).eq("status",1).list();
       List<Map<String,Object>> list=new ArrayList<>();
         for (CoachStudent coachStudent:coachStudents){
             HashMap<String, Object> map = new HashMap<>();
             int studentId =coachStudent.getStudentId();
             map.put("studentId",studentId);
             map.put("name", userinfoServiceImpl.query().eq("user_id",studentId).one().getRealName());
             list.add(map);
         }
       return Result.Success(list);
   }
    //教练的课程
    @RequestMapping("allcoursebycoachId")
    public  Result allcoursebycoachId(HttpServletRequest request){
        int coachId=request.getIntHeader("userId");
        List<CoachCourse> coachCourses = coachCourseServiceImpl.query().eq("coach_id", coachId).list();
        List<Course> li=new ArrayList();
        for (CoachCourse coachCourse:coachCourses){
            li.add(courseServiceImpl.query().eq("course_id",coachCourse.getCourseId()).one());
        }
        return Result.Success(li);
    }
    //查询当前用户教练的的所有订单 所有信息存在一个list
    @RequestMapping("selectordersbycoachid")
    public Result selectordersbycoachid(HttpServletRequest request){
        int  coachId = request .getIntHeader("userId");
        List<Orders> list=ordersServiceImpl.query().eq("coach_id", coachId).list();
        List<Map<String,Object>> li=new ArrayList<>();
        for (Orders order:list){
            Map<String ,Object> map=new HashMap<>();
            //查询学员的id
            map.put("ordersId",order.getOrdersId());
            int studentId=order.getStudentId();
            map.put("studentId",studentId);
            Userinfo studentinfo= userinfoServiceImpl.query().eq("user_id",studentId).one();
            //学员的姓名
            String name=studentinfo.getRealName();
            map.put("name",name);
            //查询上课时间
            CoachTime coachTime= coachTimeServiceImpl.query().eq("coach_time_id",order.getCoachTimeId()).one();
//           上课的week
             int  week= coachTime.getWeek();
            //查询上课的具体时间(上课时段)
            Time time= timeServiceImpl.query().eq("time_id", coachTime.getTimeId()  ).one();
            String timedesc=time.getTimeDescription();
            String coursetime="星期"+week+timedesc;
            map.put("timedesc",coursetime);
            //查询课程名字
            Course course= courseServiceImpl.query().eq("course_id",order.getCourseId()).one();
            String coursename=course.getCourseName();
            map.put("coursename",coursename);
            order.setCourse(course);
            //查询订单的状态
            map.put("status",order.getStatus());
            //课时长度
            map.put("curselength",order.getCourseLength());
            li.add(map);
        }
        return Result.Success(li);
    }



//查询当前用户学员的的所有订单 所有信息存在一个list
    @RequestMapping("selectordersbyuserid")
    public Result selectorders( HttpServletRequest request){
        int studentId=request.getIntHeader("userId");
        List<Orders> list=ordersServiceImpl.query().eq("student_id", studentId).ne("status",0).list();
        for (Orders order:list){
        //查询对应教练信息
        CoachInfo coachInfo= CoachInfoServiceImpl.query().eq("user_id",order.getCoachId()).one();
        order.setCoachInfo(coachInfo);
            //查询上课时间
        CoachTime coachTime= coachTimeServiceImpl.query().eq("coach_time_id",order.getCoachTimeId()).one();
        order.setCoachTime(coachTime);
        //查询上课的具体时间(上课时段)
            Time time= timeServiceImpl.query().eq("time_id", coachTime.getTimeId()).one();
            coachTime.setTime(time);
            //查询课程名字
           Course course= courseServiceImpl.query().eq("course_id",order.getCourseId()).one();
           order.setCourse(course);
        }
        System.out.println(list);
        return Result.Success(list);
    }
    //教练测单(学员未支付的情况下的情况下)
    @RequestMapping("deleteorders")
    public Result deleteorders(int studentId,int coachId){
    //根据条件删除
        QueryWrapper<Orders> wrapper=new QueryWrapper();
        wrapper.eq("student_id",studentId).eq("coach_id",coachId);
        ordersServiceImpl.remove(wrapper);
        System.out.println( ordersServiceImpl.list(wrapper));
        return Result.Success("测单成功");
    }
    //0是学员不可见(未发起支付)  1(一发起支付)未支付 2同意(系统转账,延时一天,支付中,暂无)  3订单完成 4是测单
    @RequestMapping("paymoney")
    @Transactional
    public Result  paymoney(int orderId,HttpServletRequest request,double paymoney,int coachId,int coachTimeId) throws IOException {
        HashMap<String, Object> map = new HashMap<>();

        //查询用户信息
        int studentId=request.getIntHeader("userid");
        map.put("userId",studentId);
        map.put("cocahId",coachId);
        map.put("money",paymoney);
        Userinfo studentuserinfo = userinfoServiceImpl.query().eq("user_id", studentId).one();
        Userinfo coachuserinfo= userinfoServiceImpl.query().eq("user_id", coachId).one();
        //查询 学员账户
        Account studentaccount=accountServiceImpl.query().eq("acccount_id",studentuserinfo.getAcccountId()).one();
        double accountmoney=studentaccount.getMoney();
        //查询教练账户户
        Account coachaccout=accountServiceImpl.query().eq("acccount_id",coachuserinfo.getAcccountId()).one();
        //判断账户余额是否充足
         if (paymoney>accountmoney){
             return  Result.Success(1);
         }
         //判断教练此时是否测单
       Orders order= ordersServiceImpl.query().eq("orders_id", orderId).one();
        int status= order.getStatus();
       if (status==4){
           return  Result.Success(4);
       }
       //系统直接扣款,修改课程确认表单 改为已经上完课了 而且自动修教练的空闲时间 改为空闲
          //扣款
//        double newstudentmoney= accountmoney-paymoney;
//
//         //加款
//        double newcoachmoney=coachaccout.getMoney()+paymoney;
//        accountServiceImpl.update().eq("acccount_id",coachuserinfo.getAcccountId()).set("money",newcoachmoney).update();
//
//        accountServiceImpl.update().eq("acccount_id",studentuserinfo.getAcccountId()).set("money",newstudentmoney).update();
//        informController.insertInform(studentId,coachId,"付款成功",1);
//        informController.insertInform(coachId,studentId,"收到一笔资金",1);

        //rabbit投递消息
        rabbitTemplate.convertAndSend(RabbitmqConfiger.ORDERS_SERVICE_EXCHANGE, RabbitmqConfiger.ORDERS_SERVICE_KEY,map,messagePostProcessor());
        //更改教练的空闲时间
        coachTimeServiceImpl.update()
                .eq("coach_id",coachId)
                .eq("coach_time_id",coachTimeId).set("status",1).update();
        //修改订单状态//本来是2的 现在只有3 表示已经完成
        ordersServiceImpl.update().eq("orders_id",orderId).set("status",3).update();
        return Result.Success(3);
    }
    //处理待发送消息
    private MessagePostProcessor messagePostProcessor(){
        return  new MessagePostProcessor() {
            @Override
            public org.springframework.amqp.core.Message postProcessMessage(Message message) throws AmqpException {
                //设置有效期时间
                message.getMessageProperties().setExpiration("60000");
                System.out.println("设置延迟时间");
                return message;
            }
        };
    }
    //查询该教练的所有的课程,
   @RequestMapping("selectcoursebycoachid")
   public Result getallcoursebyid(HttpServletRequest request){
        //查询拥有的课程id
      int coachId=request.getIntHeader("userId");
       List<CoachCourse> lis=coachCourseServiceImpl.query().eq("coach_id",coachId).list();
       List<Course> courses=new ArrayList<Course>();
       for (CoachCourse coachCourse:lis){
           courses.add(courseServiceImpl.query().eq("course_id",coachCourse.getCourseId()).one());
       }
        return  Result.Success(courses);
   }

   //查询教练所有的上课时间(空闲),周几,时间段
    @RequestMapping("selecttimebycoachid")
    public  Result getallcoachtime(HttpServletRequest  request){
        int coachId=request.getIntHeader("userId");
      List<CoachTime> lis=coachTimeServiceImpl.query().eq("coach_id",coachId).eq("status",1).list();
      for (CoachTime coachTime:lis){
         Time time= timeServiceImpl.query().eq("time_id",coachTime.getCoachTimeId()).one();
          coachTime.setTime(time);
      }
        return  Result.Success(lis);
    }
    //查询教练的所有的交易次数 成功次数 失败次数 好评次数 中 差次数
    @RequestMapping("selectordercount")
    public  Map selectordercount(HttpServletRequest request ,int coachId){
       int studentId=request.getIntHeader("userId");
        System.out.println(studentId);
        System.out.println(coachId);
        Map<String,Object> map=new HashMap();
        //次数
       int allcount= ordersServiceImpl.query().eq("coach_id",coachId).count();
       //成功
        int faultcount=ordersServiceImpl.query()
                .eq("coach_id",coachId).eq("status",2).count();
        //失败
        int successcount=ordersServiceImpl.query()
                .eq("coach_id",coachId).eq("status",3).count();
//         好评次数
        int goodcomment=commentServiceImpl.query().eq("coach_id",coachId).eq("level",1).count();
//
        int middlecomment=commentServiceImpl.query().eq("coach_id",coachId).eq("level",2).count();
        int badcomment=commentServiceImpl.query().eq("coach_id",coachId).eq("level",3).count();
        map.put("allcount",allcount);
        map.put("faultcount",faultcount);
        map.put("successcount",successcount);
        map.put("goodcomment",goodcomment);
        map.put("middlecomment",middlecomment);
        map.put("badcomment",badcomment);
        //查询教练的基本信息
       CoachInfo coachInfo= CoachInfoServiceImpl.query().eq("user_id",coachId).one();
       //电话号码:
        String phone = coachInfo.getPhone();
        //认证状态
        coachInfo.getIndentification();
//        信息等级
        Integer telLevel = coachInfo.getTelLevel();
//        课时费
        double charge=coachInfo.getCharge();
        map.put("charge",charge);
//        空闲时间
        List<CoachTime> coachTimes= coachTimeServiceImpl.query().eq("coach_id",coachId).eq("status",1).list();
        String timedesc="";
        for (CoachTime coachTime: coachTimes){
            Time time = timeServiceImpl.query().eq("time_id", coachTime.getTimeId()).one();
            if (time!=null)
            timedesc=timedesc+"//"+"星期"+coachTime.getWeek()+time.getName();
        }
          map.put("freetime",timedesc);
        //查询课程的种类
        String coursedesc="";
        List<CoachCourse> coachcourses= coachCourseServiceImpl.query().eq("coach_id",coachId).list();
        for (CoachCourse coachCourse: coachcourses){
            Course course = courseServiceImpl.query().eq("course_id", coachCourse.getCourseId()).one();
            if (course!=null)
                coursedesc=coursedesc+"//"+course.getCourseName();
        }
        map.put("course",coursedesc);
        //查询和教练的关系(未关注 已关注 相互关注)
        Attention attention1 = attentionServiceImpl.query().eq("oneself_id", studentId).eq("others_id", coachId).one();
        Attention attention2 =attentionServiceImpl.query().eq("oneself_id", coachId).eq("others_id", studentId).one();
        String attentiondesc="";
        if (attention1!=null)  attentiondesc="已关注";
        if (attention1!=null&&attention2!=null) attentiondesc="相互关注";
        if (attention1==null)  attentiondesc="未关注";
        map.put("attentiondesc",attentiondesc);
        Userinfo userinfo = userinfoServiceImpl.query().eq("user_id", coachId).one();
        //查询真实姓名
        String realName = userinfo.getRealName();
        map.put("realName",realName);
        //电话
        map.put("phone",userinfo.getTelphone());
        //查询信息权限
        Integer infoLevel = userinfo.getInfoLevel();
        map.put("infoLevel",infoLevel);
        map.put("coachId",coachId);
        map.put("studentId",studentId);
        return map;
    }
}

